package com.xy.demo.controller;

import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentBuilder;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class FlowController {
    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    ProcessEngine processEngine;

    @GetMapping("/deploy")
    public void deployFlow() {
        try {

            String filePath1 = "demo1.bpmn20.xml";
            String filePath2 = "demo-sub-process.bpmn20.xml";
            DeploymentBuilder deploymentBuilder = repositoryService
                    .createDeployment()
                    .addClasspathResource(filePath1).addClasspathResource(filePath2);
            Deployment deployment = deploymentBuilder.deploy();
            System.out.println("成功：部署工作流成：" + filePath1 + " " + filePath2);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败：部署工作流：" + e);
        } // end catch
    }

    @GetMapping("/add")
    public String addExpense(@RequestParam String userId) {
        //启动流程
        HashMap<String, Object> map = new HashMap<>(4);

        //name="客服代表" flowable:candidateGroups="${customerServiceId}"

        map.put("userId", userId);

        //<process id="adviceApply" name="投诉建议" isExecutable="true">
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("demo1", map);
        return "提交成功.流程Id为：" + processInstance.getId();
    }

    /**
     * 流转
     *
     * @param processId 流程id
     */
    @GetMapping("/apply")
    public String apply(@RequestParam String processId, @RequestParam String userId) {
        //查询当前办理人的任务ID
        Task task = taskService.createTaskQuery()
                //使用流程实例ID
                .processInstanceId(processId)
                //任务办理人
                .singleResult();
        if (task == null) {
            throw new RuntimeException("流程不存在");
        }
        //通过审核
        HashMap<String, Object> map = new HashMap<>();
        map.put("taskUser", userId);
        taskService.complete(task.getId(), map);
        return "processed ok!";
    }
}
